package com.sun.sort.bubbling;

import java.util.Arrays;

/*
冒泡排序的实现思路
1
 */
public class bubbling1 {
    public static void main(String[] args) {
        int[] arr = {3,9,-1,10,20};
        int[] ordinary = ordinary(arr);
        for (int i : ordinary) {
            System.out.print(i + "\t");
        }
        System.out.println("arr" + Arrays.toString(arr));
        System.out.println("==================");
        int[] optimize = optimize(arr);
        for (int i : optimize) {
            System.out.print(i + "\t");
        }
    }
    public static int[] ordinary(int[] arr){
        int sum = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]){
                    sum = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = sum;
                }
            }
            System.out.println("第" + (i + 1) + "趟，数组顺序" + Arrays.toString(arr));
            System.out.println();
        }
        return arr;
    }

    public static int[] optimize(int[] arr){
        int sum = 0;
        boolean flag = false;
        for (int i = 0; i < arr.length - 1; i++) {
            flag = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]){
                    sum = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = sum;
                    flag = true;
                }
            }
            System.out.println("第" + (i + 1) + "趟，数组顺序" + Arrays.toString(arr));
            System.out.println();
            if (!flag){
                //一趟排序中，一次交换都没有，说明已经排序好了
                break;
            }

        }

        return arr;
    }
}
